package liecai_class.day06;

import java.util.concurrent.Exchanger;

/**
 * 交换机 Exchanger
 */
public class Demo08 {
    private static Exchanger<String> exchanger = new Exchanger<>();
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    //此方法将会接受当前线程消息，并获取对方线程消息返回
                    //如果未达到交换的条件，则进入阻塞，直到交换可以进行，才会放行
                    String msg = exchanger.exchange("天王盖地虎!");
                    System.out.println("线程1收到消息:"+msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    //此方法将会接受当前线程消息，并获取对方线程消息返回
                    //如果未达到交换的条件，则进入阻塞，直到交换可以进行，才会放行
                    String msg = exchanger.exchange("小鸡炖蘑菇!");
                    System.out.println("线程2收到消息:"+msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
